const WebSocket = require('ws');
const messageManage = require('./messageManage');

const port = process.env.WEBSOCKET_PORT || 2883;

// 创建WebSocket服务器
const wss = new WebSocket.Server({ port: port });

console.log(`启动Websocket服务，端口：${port}`);

// 连接到服务器的客户端列表
const clientList = [];

// Websocket客户端
class WSClient {

    constructor(ws) {
        this.ws = ws;
        // 接收客户端消息
        ws.on('message', (message) => {
            console.log(`Received message: ${message}`);
            const obj = JSON.parse(message);
            const command = obj.command;

            // 根据传过来的端口号给客户端分组
            if (command === 'port') {
                if (this.subscriber) {
                    return;
                }
                const port = message.split(':')[1];
                this.port = port;
                this.subscriber = messageManage.subscribe(port, function(data) {
                    ws.send(data);
                });
            } else if (message.startsWith('send')) {
                if (this.port) {
                    console.warn('还没有注册端口');
                    return;
                }
                const content = obj.content;
                messageManage.addMessage(this.port, content);
            }
        });

        // 当客户端关闭连接
        ws.on('close', () => {
            // 客户端关闭时，取消订阅
            if (this.subscriber) {
                messageManage.unsubscribe(this.port, this.subscriber);
            }
            console.log(`Client disconnected.`);
        });
    }

}

// 当客户端连接时
wss.on('connection', (ws) => {
    const client = new WSClient(ws);
    clientList.push(client);
});
